package com.learning.spring.cloud.service.impl;

import com.learning.spring.cloud.domain.service.OrderDomainService;
import com.learning.spring.cloud.dto.CreateOrderResult;
import com.learning.spring.cloud.dto.OrderDto;
import com.learning.spring.cloud.dto.OrderItemDto;
import com.learning.spring.cloud.external.dto.ProductDto;
import com.learning.spring.cloud.external.dto.ProductInventoryDto;
import com.learning.spring.cloud.external.service.InventoryService;
import com.learning.spring.cloud.external.service.ProductService;
import com.learning.spring.cloud.service.OrderService;
import lombok.extern.java.Log;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Optional;
import java.util.UUID;

@Log
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDomainService orderDomainService;

    @Autowired
    private ProductService productService;

    @Autowired
    private InventoryService inventoryService;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Override
    public CreateOrderResult createOrder(OrderDto orderDto) {
        log.info("receive create order request");
        for (OrderItemDto orderItemDto : orderDto.getOrderItemList()) {
            // 不考虑性能问题
            Optional<ProductDto> product = productService.findProductByCode(orderItemDto.getProductCode());
            if (product.isEmpty()) {
                log.info("产品%s已下架".formatted(orderItemDto.getName()));
                return new CreateOrderResult(false, "产品%s已下架".formatted(orderItemDto.getName()), null);
            }
            Optional<ProductInventoryDto> inventory = inventoryService.findInventoryInfoByProductCode(orderItemDto.getProductCode());
            if (inventory.isEmpty() || inventory.get().getQuantity() <= 0) {
                log.info("%s库存不足".formatted(orderItemDto.getName()));
                return new CreateOrderResult(false, "%s库存不足".formatted(orderItemDto.getName()), null);
            }
            orderItemDto.setPrice(product.get().getPrice());
            orderItemDto.setDiscount(BigDecimal.valueOf(1));
        }

        orderDto.setOrderNo(UUID.randomUUID().toString());
        orderDto.getOrderItemList().stream()
                .map(i -> i.getPrice().multiply(i.getDiscount()))
                .reduce((a, b) -> a.add(b))
                .ifPresent(p -> orderDto.setTotalPrice(p));

        OrderDto updated = orderDomainService.save(orderDto);
        log.info("订单（单号：%s）创建成功".formatted(orderDto.getOrderNo()));
        rabbitTemplate.convertAndSend("notification.queue", "订单（单号：%s）创建成功".formatted(orderDto.getOrderNo()));
        return new CreateOrderResult(true, "", updated);
    }

    public OrderDto findByOrderNo(String orderNo) {
        return orderDomainService.findByOrderNo(orderNo);
    }

}
